'use strict';

angular.module('hackathonApp')
    .controller('IssuesListCtrl', function ($scope, IssueService) {
        $scope.issues=[];

        //filter
        $scope.filterOptions = {
            filterText: "",
            useExternalFilter: true
        };

        //paging
        $scope.totalServerItems = 0;
        $scope.pagingOptions = {
            pageSizes: [5, 10, 15,20],
            pageSize: 12,
            currentPage: 1
        };

        //sort
        $scope.sortInfo = {
            fields: ['visible_id'],
            directions: ['DESC']
        };

        $scope.optionButtons = '<a class="btn btn-success btn-xs" href="#/issues/{{row.entity.issue_id}}/edit"><i class="icon-edit"></i> Edit</a><button class="btn btn-danger btn-xs" ng-click="deleteIssue($index)"><i class="icon-trash"></i> Delete</button>';

        // grid
        $scope.gridOptions = {
            data: "issues",
            columnDefs: [
                { field: "visible_id", displayName: "#", width: "60" },
                { displayName:'Options',cellTemplate:$scope.optionButtons},
                { field: "issue_title", displayName: "Title",},
                { field: "project_title", displayName: "Project"},
                { field: "assignee", displayName: "Assigned To"},
                { field: "priority", displayName: "Priority"},
                { field: "status", displayName: "Status"},
                { field: "modified", displayName: "Modified"}
            ],
            enablePaging: true,
            pagingOptions: $scope.pagingOptions,
            filterOptions: $scope.filterOptions,
            keepLastSelected: true,
            multiSelect: false,
            showColumnMenu: true,
            showFilter: true,
            showFooter: true,
            sortInfo: $scope.sortInfo,
            totalServerItems: "totalServerItems",
            useExternalSorting: true,
            i18n: "en"
        };

        $scope.refresh = function () {
            setTimeout(function () {
                var sb = [];
                for (var i = 0; i < $scope.sortInfo.fields.length; i++) {
                    sb.push($scope.sortInfo.fields[i]+" "+$scope.sortInfo.directions[i]);
                }

                var params = {
                    searchText: $scope.filterOptions.filterText.toLowerCase(),
                    pageNumber: $scope.pagingOptions.currentPage,
                    pageSize: $scope.pagingOptions.pageSize,
                    sortInfo: sb.join(",")
                };

                IssueService.query(params,function(response) {
                    $scope.totalServerItems = response.totalItems;
                    /*var total=response.items.length;
                    for(i=0;i<total;i++) {
                        //response.items[i].visible_id="<a href='#'>blah</a>";
                    }*/
                    $scope.issues = response.items;
                });
            }, 100);
        };

        //watches
        $scope.$watch('pagingOptions', function (newVal, oldVal) {
            if (newVal !== oldVal) {
                $scope.refresh();
            }
        }, true);

        $scope.$watch('filterOptions', function (newVal, oldVal) {
            if (newVal !== oldVal) {
                $scope.refresh();
            }
        }, true);

        $scope.$watch('sortInfo', function (newVal, oldVal) {
            if (newVal !== oldVal) {
                $scope.refresh();
            }
        }, true);

        $scope.deleteIssue = function (idx) {
            var issue = $scope.issues[idx];

            IssueService.delete({ id: issue.issue_id }, function() {
                $scope.issues.splice(idx, 1);
                Messenger().post({message: "Issue "+ issue.visible_id +" Deleted", type:"info"});
            });
        };

        $scope.refresh();
    });

angular.module('hackathonApp')
    .controller('IssuesFormCtrl', function ($scope, $routeParams, IssueService, $location, PicklistService) {
        if($routeParams.id) {
            IssueService.get({id: $routeParams.id}, function(response) {
                $scope.form_title = response.visible_id + " - " + response.issue_title;
                $scope.issue = response;
            });
        } else {
            $scope.form_title = "Issue Form";
            $scope.issue = new IssueService();
        }

        PicklistService.query({table: 'project',id_field: 'project_id',value_field:'title', where: "1=1"}, function(response) {
            $scope.projects = response;
            PicklistService.query({table: 'contact',id_field: 'contact_id',value_field:'fullname', where: "org_id='symp'"}, function(response) {
                $scope.assignees = response;
            });
        });

        $scope.save = function () {
            var promise;
            if($scope.issue.issue_id) {
                promise = $scope.issue.$update();
            } else {
                promise = $scope.issue.$save();
            }

            promise.then(function(issue) {
                Messenger().post({message: "Issue " + issue.issue_title + " Saved", type:"success"});
                return $location.path('/issues');
            })
        }

        $scope.deleteIssue = function () {
            IssueService.delete({ id: $scope.issue.issue_id });
            Messenger().post({message: "Issue "+ $scope.issue.visible_id +" Deleted", type:"info"});
            return $location.path('/issues');
        };
    });
